#include <rtthread.h>
#include <rtdevice.h>

#ifndef BSP_LED0_PIN_NAME
#define BSP_LED0_PIN_NAME "PD.14"
#endif

struct ledmsg
{
    int led;
    int sec;
    int freq;
};

static struct rt_messagequeue mq;
static int msg_pool[16];

static void led_thread(void *param)
{
    rt_base_t led0;
    struct ledmsg msg;
    int ms;
    rt_tick_t start, diff;

    (void)param;

    led0 = rt_pin_get(BSP_LED0_PIN_NAME);

    rt_pin_mode(led0, PIN_MODE_OUTPUT);

_waitmsg:
    rt_mq_recv(&mq, &msg, sizeof(msg), RT_WAITING_FOREVER);
    start = rt_tick_get();

    ms = 1000/msg.freq;
    ms /= 2;

    while (1)
    {
        diff = rt_tick_get() - start;
        if (diff > rt_tick_from_millisecond(msg.sec * 1000))
            goto _waitmsg;

        rt_pin_write(led0, 1);
        rt_thread_mdelay(ms);
        rt_pin_write(led0, 0);
        rt_thread_mdelay(ms);
    }
}

int led_set_blink(int led, int sec, int freq)
{
    struct ledmsg msg;

    msg.led = led;
    msg.sec = sec;
    msg.freq = freq;

    return rt_mq_send(&mq, &msg, sizeof(msg));
}

int task_led_init(void)
{
    rt_thread_t tid;
    int ret = -1;

    rt_mq_init(&mq, "mqt",
               &msg_pool[0],        
               128 - sizeof(void*), 
               sizeof(msg_pool),    
               RT_IPC_FLAG_FIFO);

    tid = rt_thread_create("led",
                           led_thread, RT_NULL,
                           512, 20, 2);

    if (tid)
        ret = rt_thread_startup(tid);

    return ret;
}
INIT_APP_EXPORT(task_led_init); //will autorun 'task_led_init'
